using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using ScottLane.VideoInbox;

namespace ScottLane.VideoInbox.Services
{
    /// <summary>
    /// A service that downloads videos.
    /// </summary>
    public partial class DownloadService : ServiceBase
    {
        private DownloadQueue downloads;
        private NotificationQueue notifications;
        private ConfigurationSettings settings;
        private bool stopped;

        public DownloadService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Thread worker = new Thread(new ThreadStart(Start));
                worker.Start();
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
            }
        }

        public void Start()
        {
            stopped = false;
            settings = ConfigurationSettings.Instance;
            downloads = new DownloadQueue();
            notifications = new NotificationQueue();

            while (!stopped)
            {
                if (downloads.Peek() != null)
                {
                    DownloadManifest manifest = downloads.Remove();
                    VideoManager manager = new VideoManager();
                    manager.DownloadContent(manifest);

                    Notification notification = new Notification(manifest.Title + " has been successfully downloaded.", manifest);
                    notifications.Add(notification);
                }

                Thread.Sleep(settings.DownloadQueuePollingInterval);
            }
        }

        protected override void OnStop()
        {
            stopped = true;
        }
    }
}
